package tech.xiaozai.rbac.controller;


import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tech.xiaozai.common.CommonPage;
import tech.xiaozai.common.restful.RestResp;
import tech.xiaozai.rbac.domain.RoleQueryInfo;
import tech.xiaozai.rbac.po.SysRole;
import tech.xiaozai.rbac.service.RoleService;

import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-17 09:00
 */
@RestController
public class SysRoleController {

    @Autowired
    private RoleService roleService;

    @PreAuthorize("hasAuthority('url:role:detail')")
    @ApiOperation(value = "用ID查角色",notes = "id为必填项")
    @RequestMapping(value = "/roles/{id}",method = RequestMethod.GET)
    public RestResp<SysRole> getById(@PathVariable Long id){
        return RestResp.ok(roleService.getById(id));
    }

    @PreAuthorize("hasAuthority('url:role:list')")
    @ApiOperation(value = "分页获取角色列表",notes = "可以传入角色名来匹配")
    @RequestMapping(value = "/roles",method = RequestMethod.GET)
    public RestResp<CommonPage<SysRole>> page(RoleQueryInfo roleQueryInfo){
        return RestResp.ok(roleService.page(roleQueryInfo.getPageNum(),roleQueryInfo.getPageSize(),roleQueryInfo));
    }


    @RequestMapping(value = "/roles/all",method = RequestMethod.GET)
    public RestResp<List<SysRole>> all(){
        return RestResp.ok(roleService.all());
    }



    @ApiOperation(value = "添加一个角色",notes = "...")
    @RequestMapping(value = "/roles",method = RequestMethod.POST)
    public RestResp<SysRole> add(@RequestBody SysRole role){
        roleService.insert(role);
        return RestResp.ok(roleService.getById(role.getId()));
    }

    @ApiOperation(value = "更新一个角色",notes = "只需设置更新字段,其它字段可以不传")
    @RequestMapping(value = "/roles",method = RequestMethod.PUT)
    public RestResp<SysRole> update(@RequestBody  SysRole role){
        roleService.update(role);
        return RestResp.ok(roleService.getById(role.getId()));
    }


    @ApiOperation(value = "删除多个角色",notes = "传入多个角色ID,以逗号隔开,例如: /roles/1,2,3")
    @RequestMapping(value = "/roles/{id}",method = RequestMethod.DELETE)
    public RestResp delete(@PathVariable("id")  List<Long> ids){
        roleService.delete(ids);
        return RestResp.ok();
    }

}
